package com.sen.security.service;

import com.sen.mapper.UserMapper;
import com.sen.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService implements UserDetailsService {

    private final static Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LOGGER.info("进入service，用户名为："+username);
        if (!StringUtils.hasLength(username)){
            throw new UsernameNotFoundException("请输入用户名！");
        }
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        User user = userMapper.getUserByName(username);
        for (String s : user.getRoles().split("-")) {
            //由于sercurity默认的role格式是ROLE_ + role，所以此处扩展，而不用保存在数据库中
            s = "ROLE_" + s;
            list.add(new SimpleGrantedAuthority(s));

        }
        return new org.springframework.security.core.userdetails.User(user.getName(),new BCryptPasswordEncoder().encode( user.getPassword()),list);
    }
}
